# Copyright 2009 http://www.yuntien.com
# Licensed under the Apache License, Version 2.0

from google.appengine.ext import db
from google.appengine.api import memcache
import cache

KEY_NAME_PREFIX = 'TAG_'

class TagInfo(db.Model):
  name = db.StringProperty(required=True, multiline=False)
  number = db.IntegerProperty(default=0)
  sort = db.IntegerProperty(default=0)
  date = db.DateTimeProperty(auto_now=True)
  
  @cache.delete_cache(cache.TAGS_KEY)
  def put(self):
    db.Model.put(self)
  
  @classmethod
  def get_or_insert_by_name(cls, tag_name, **kwds):
    try:      
      return TagInfo.get_or_insert(KEY_NAME_PREFIX+tag_name, **kwds)
    except:
      return None  

  @classmethod
  def get_by_name(cls, tag_name):
    return TagInfo.get_by_key_name(KEY_NAME_PREFIX+tag_name)

  @classmethod
  def get_tags(cls):
    limit=30      
    data = memcache.get(cache.TAGS_KEY)
    if data is not None:
      return data
    else:
      data = TagInfo.all().order('sort').order('-number').fetch(limit)
      memcache.add(cache.TAGS_KEY, data, cache.COMMON_TIME_OUT)
      return data
